package com.lintesis.lintesisview.webgui.users;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zkplus.databind.BindingListModel;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Paging;
import org.zkoss.zul.SimpleConstraint;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.api.Combobox;
import org.zkoss.zul.api.Intbox;
import org.zkoss.zul.api.Listbox;


import com.lintesis.lintesismodel.common.hibernate.GenericDAO;
import com.lintesis.lintesismodel.common.hibernate.HibernateSearchObject;
import com.lintesis.lintesismodel.users.IdType;
import com.lintesis.lintesismodel.users.Role;
import com.lintesis.lintesismodel.users.User;
import com.lintesis.lintesisview.common.ABMDialogCtrl;
import com.lintesis.lintesisview.common.BoException;
import com.lintesis.lintesisview.common.menu.UserWorkspace;

import com.trg.search.Filter;
import com.trg.search.SearchResult;

public class UserDialogCtrl extends ABMDialogCtrl<User>
{

//	@Override
//	public void doSave() throws InterruptedException
//	{
//		super.doSave();
//		User.exportWorkers();
//	}

	private static final long serialVersionUID = 8227495170707480800L;
	static final String rightPreffix = "user.dialog.";

	// GUI Components
//	Textbox tbPersonId;
	Textbox tbName;
	Textbox tbSurname;
	Textbox tbLogin;
	Textbox tbPassword1;
	Textbox tbPassword2;
	Checkbox chEnable;
	Textbox tbEmail;
	Textbox tbPhone;
	Textbox tbIdNumber;
	Combobox cbIdTypes;
	BindingListModel lmIdTypes;
	Label lbIdType;
	Label lbIdNumber;
	Label lbName;
	Label lbSurname;
	Label lbLogin;
	Label lbPassword;
	Label lbPassword2;
	int isNull = 0;

	int i = 0;
	
	// availble Rols
	BindingListModelList listModelRols;
	Listbox listboxAvailbleRols;

	Paging pagingListRoles;

	Listheader lhName;
	Listheader lhDescription;

	Listheader lhAssignedRoleName;
	Listheader lhAssignedRoleDescription;

	// Role searching related objects
	GenericDAO<Role> gdaoRols = new GenericDAO<Role>(UserWorkspace.getInstance().gethSession());
	HibernateSearchObject<Role> hsoRols = new HibernateSearchObject<Role>(Role.class);
	HashMap<String, Object> filterRols = new HashMap<String, Object>();

	@Override
	protected void doSetClearComponents()
	{
//		clearComponents.add(tbPersonId);
		clearComponents.add(tbName);
		clearComponents.add(tbSurname);
		clearComponents.add(tbLogin);
		clearComponents.add(tbPassword1);
		clearComponents.add(tbPassword2);
//		if(this.entity.getId()!=null){
//		clearComponents.add(chEnable);
//		}
		clearComponents.add(tbPhone);
		clearComponents.add(tbEmail);
		clearComponents.add(tbIdNumber);
		clearComponents.add(cbIdTypes);
	}

	@Override
	protected void doSetFieldProperties()
	{
//		tbName.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
//		tbSurname.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
//		tbLogin.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
//		tbPassword1.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
//		tbPassword2.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
////		tbPhone.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
////		tbEmail.setConstraint(new EmailConstraint());
//		comboIdTypes.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
//		tbIdNumber.setConstraint(new SimpleConstraint(SimpleConstraint.NO_EMPTY));
//		tbBoxAccessPass1.setConstraint(new NumberConstraint());
//		tbBoxAccessPass2.setConstraint(new NumberConstraint());
	}

	@Override
	protected void doSetReadOnlyComponents()
	{
		roComponents.add(tbName);
		roComponents.add(tbSurname);
		roComponents.add(tbLogin);
		roComponents.add(tbPassword1);
		roComponents.add(tbPassword2);
		roComponents.add(listboxAvailbleRols);
		roComponents.add(tbPhone);
		roComponents.add(tbEmail);
		roComponents.add(tbIdNumber);
		roComponents.add(cbIdTypes);
//		if(this.entity.getId()!=null){
//		roComponents.add(chEnable);
//		}
	}

	@Override
	protected void doSetValidation() throws Exception {
//		if((entity.getIdType()==null) || (cbIdTypes.getValue().isEmpty() == true)){
//			lbIdType.setStyle("color:red");
//			isNull= 1;
//			}
//		else{
//			lbIdType.setStyle("color:black");
//		}
//		if((entity.getIdNumber()==null) || (tbIdNumber.getValue().isEmpty() == true)){
//			lbIdNumber.setStyle("color:red");
//			isNull= 1;
//		}
//		else{
//			lbIdNumber.setStyle("color:black");
//		}		
//		if((entity.getName()==null) || (tbName.getValue().isEmpty() == true)){
//			isNull= 1;
//			lbName.setStyle("color:red");
//		}
//		else{
//			lbName.setStyle("color:black");
//		}
//		if((entity.getSurname()==null) || (tbSurname.getValue().isEmpty() == true)){
//			isNull= 1;
//			lbSurname.setStyle("color:red");
//		}
//		else{
//			lbSurname.setStyle("color:black");
//		}
//		if((entity.getLogin()==null) || (tbLogin.getValue().isEmpty() == true)){
//			isNull= 1;
//			lbLogin.setStyle("color:red");
//		}
//		else{
//			lbLogin.setStyle("color:black");
//		}
//		if((entity.getPassword()==null) || (tbPassword1.getValue().isEmpty() == true) || (tbPassword2.getValue().isEmpty() == true)){
//			isNull= 1;
//			lbPassword.setStyle("color:red");
//			lbPassword2.setStyle("color:red");
//		}
//		else{
//			lbPassword.setStyle("color:black");
//			lbPassword2.setStyle("color:black");
//		}
//		if(isNull==1){
//			isNull = 0;
//			this.doSetClearComponents();
//			throw new BoException("Debe completar los datos obligatorios indicados con rojo");			
//		}		
		
		if (!tbPassword1.getValue().equals(tbPassword2.getValue()))
			throw new BoException(Labels.getLabel("twoPasswordsEnteredMustMatch"));
		
		if(entity.getRols().isEmpty()){
			throw new BoException("Debe seleccionar un Rol");
		}
	}

	@Override
	protected void fillBussinesObject()
	{
		chEnable.setDisabled(true);
		if (entity.getPassword() != null && entity.getPassword().length() > 0)
			tbPassword2.setText(entity.getPassword());
		entity.setBirthday(new GregorianCalendar(2000, 01, 01));
		entity.setGender(1);
	}

	@Override
	protected void fillComboBoxs()
	{
		doSearchRols();
		try
		{
			lmIdTypes = new BindingListModelList(new GenericDAO<IdType>(UserWorkspace.getInstance().gethSession()).getByBussinessObject(new IdType()), true);
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected User getNewEntidad()
	{
		User sysUser = new User();
		sysUser.setUserState(true);
		chEnable.setDisabled(true);
		return sysUser;
	}

	@Override
	protected String getRightPreffix()
	{
		return rightPreffix;

	}

	public BindingListModelList getListModelRols()
	{
		return listModelRols;
	}

	public void setListModelRols(BindingListModelList listModelRols)
	{
		this.listModelRols = listModelRols;
	}

	protected void doSearchRols()
	{
		if(this.getEntidad().getId() == null){	
			
			hsoRols.clearFilters();
//			if(UserWorkspace.getInstance().getUser().getAllowedCompanies().size()>0)
//				hsoRols.addFilterSome("companies", Filter.in("", UserWorkspace.getInstance().getUser().getAllowedCompanies()));
//			if(UserWorkspace.getInstance().getUser().getAllowedStations().size()>0)
//				hsoRols.addFilterSome("stations", Filter.in("", UserWorkspace.getInstance().getUser().getAllowedStations()));
			
			hsoRols.addSortAsc("roleName");
			SearchResult<Role> initialList = gdaoRols.getSRByHashMap(hsoRols, 0, 0, filterRols,false);
			
			listModelRols = new BindingListModelList(initialList.getResult(), true);
			binder.loadAll();

		}
		else{
			hsoRols.addSortAsc("roleName");
			SearchResult<Role> initialList = gdaoRols.getSRByHashMap(hsoRols, 0, 0, filterRols);
	
			listModelRols = new BindingListModelList(initialList.getResult(), true);
			binder.loadAll();
		}

	}

	public void onCheck$chShowAllRols(Event event)
	{
		doClearSearchValuesRols();
		doSearchRols();

	}

	public void doClearSearchValuesRols()
	{
		hsoRols.clear();
		filterRols.clear();
	}

	@Override
	public String getEntityName()
	{
		return "User";
	}

	public BindingListModel getLmIdTypes()
	{
		//ver si lo siguiente se puede hacer de otra forma, quizás se debería modificar el ABMDialog
		//hablarlo con Maty
		int p = 0;
		if(i==4 && this.entity.getId()!= null){
			chEnable.setDisabled(false);
			i = 0;
			p = 1;
		}
		if(i!=4){
			if(p==0){
				chEnable.setDisabled(true);
			}		
			if(i==2){
				chEnable.setDisabled(false);
			}
			
			i++;
		}
		return lmIdTypes;
	}

	public void setLmIdTypes(BindingListModel lmIdTypes)
	{
		this.lmIdTypes = lmIdTypes;
	}
}
